<template>
  <div class="cropper">
    <div @click="onChooseImageClick">
      <slot></slot>
    </div>
    <el-dialog title="裁剪图片" width="1000px" append-to-body :visible.sync="isDialogVisible" :before-close="resetCropper">
      <div class="text-666 text-14 d-flex">
        <div class="flex-1">
          <div class="pb-16">选择合适的尺寸</div>
          <div style="height: 400px">
            <vueCropper ref="cropper" v-bind="cropperOptions" @real-time="realTime"></vueCropper>
          </div>
        </div>
        <div class="flex-1 ml-24">
          <div class="pb-16">图片预览</div>
          <div class="show-preview overflow-hidden"
            :style="{ 'width': previews.w + 'px', 'height': previews.h + 'px' }">
            <div :style="previews.div">
              <img :src="previews.url" :style="previews.img" alt="">
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="resetCropper">取消</el-button>
        <el-button type="primary" :loading="isSaving" @click="onConfirm">{{ autoUpload ? '确认并上传' : '确认' }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="MCropper">
import { ref, computed, onMounted } from 'vue'
import { VueCropper, CropperOptions } from 'vue-cropper'


const props = defineProps<{
  options: CropperOptions,
  autoUpload?: boolean
}>()

const fileList = ref([])
const cropperRef = ref()
const isDialogVisible = ref(true)
const isSaving = ref(false)
// const realTime = ref('')
const previews: any = ref({ url: '' })

const option = ref({
  centerBox: true,
  outputType: 'png',
  img: '' // 动态试试预览的图片地址
})

const cropperOptions = computed(() => {
  return { ...option.value, ...props.options }
})

const onChooseImageClick = () => { }

const getCropBlob = () => {
  // file 其实是 Blob类型
  return new Promise<{ url: string; file: File }>((resolve, reject) => {
    (cropperRef.value as VueCropper).getCropBlob(data => {
      const url = window.URL.createObjectURL(data)
      resolve({ url, file: data as File })
    })
  })
}

const onConfirm = async () => {
  isSaving.value = true
  try {
    const data = await getCropBlob()
    // const url = await this.$wxtCloud.uploadFileToCloud(data)
    // this.$emit('success', url)
    // resetCropper()
  } catch (error) {
    console.log(error)
    // ElMessage.error('文件上传失败,请刷新后重试');
  }
  isSaving.value = false
}

// 实时预览
const realTime = computed((data: { url: string }) => previews.value = data)

// 重置图片切取
const resetCropper = () => {
  fileList.value = []
  isDialogVisible.value = false
}

onMounted(() => { })

</script>

<style lang="less" scoped>
</style>
